import React, { useLayoutEffect } from 'react';
import {
  View,
  Image,
  Text,
  navigateTo,
  hideMenuButton,
  exitMiniProgram,
  router,
  publishDps,
} from '@ray-js/ray';
import { useDevice, useProps } from '@ray-js/panel-sdk';
import { getCachedLaunchOptions } from '@/api/getCachedLaunchOptions';
import { CellGroup, NavBar, Cell, Switch } from '@ray-js/smart-ui';
import styles from './index.module.less';
import Strings from '@/i18n';
import { useThrottleFn } from 'ahooks';
import { useSwitchInfo } from '@/hooks/useSwitchInfo';
import { SwitchWihtLoading } from '../groupInfo';
import { useWaterControlInfo } from '@/hooks/useWaterControlInfo';

export const decodeArea = (area: string) => {
  // 将十六进制字符串转换为8位二进制字符串
  const binary = parseInt(area, 16).toString(2).padStart(8, '0');
  return binary.split('').reverse().join('');
};

// 添加encodeArea方法，将8位二进制字符串转换为十六进制字符串
export const encodeArea = (binary: string) => {
  // 将二进制字符串转换为2位十六进制字符串
  return parseInt(binary, 2).toString(16).padStart(2, '0');
};

export function AreaAndSwitch() {
  const { all_switch: allSwitch, irrigation_area: irrigationArea } = useProps();

  const area = irrigationArea?.length === 2 ? decodeArea(irrigationArea) : '11111';

  const dpsInfo = useWaterControlInfo();

  const waterDps = ['countdown_1', 'countdown_3', 'countdown_5', 'usb_countdown_1', 'countdown_9'];

  const showDevie = waterDps
    .map(item => {
      const res = dpsInfo.find(group => group.water.timerDpName === item);
      return res.water;
    })
    .filter(item => !item.hide && !item.isOffLine);

  const handleJump = useThrottleFn(
    (code: string) => {
      router.push(`/${code}`);
    },
    { wait: 80 }
  ).run;

  const areaValue = showDevie
    .map((i, index) => ({
      ...showDevie[index],
      power: area[index],
    }))
    .filter(item => item.power === '1')
    .map((item, index) => item.name)
    .join(',');

  return (
    <CellGroup className={styles.weather} inset insetBorderRadius={12}>
      <Cell title={Strings.getLang('allArea')}>
        <SwitchWihtLoading
          checked={allSwitch}
          onChange={value => {
            publishDps({
              all_switch: !allSwitch,
            });
          }}
        />
      </Cell>
      <Cell
        title={Strings.getLang('irrigation_area')}
        value={areaValue?.length > 18 ? areaValue.slice(0, 15) + '...' : areaValue}
        isLink
        onClick={() => handleJump('area')}
      />
    </CellGroup>
  );
}

export default AreaAndSwitch;
